//
//  SNSMarkLabelView.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-8-1.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "SNSMarkLabelView.h"

#define kPointerSize        30

#define kLabelInsetLeft     34
#define klabelInsetRight    5
#define kLabelInsetTop      8
#define kLabelInsetBottom   8

#define kSegueAddMark       @"toAddMarkView"
#define kSNSMarkPosX        @"posX"
#define kSNSMarkPosY        @"posY"
#define kSNSMarkDirection   @"direction"
#define kSNSMarkContent     @"content"

@interface SNSMarkLabelView()
@property (strong, nonatomic) IBOutlet UIImageView *pointer;

@property (strong, nonatomic)UIImageView *bgImage;
@property (strong, nonatomic)UIImageView *arrow;

@property (weak, nonatomic) IBOutlet UILongPressGestureRecognizer *popOption;

//@property(assign, nonatomic)BOOL shownActionSheet;
@end


@implementation SNSMarkLabelView


-(instancetype)initWithText:(NSString *)text pos:(CGPoint)pos direction:(SNSMarkDirection)direction{
    CGSize size = [self calcFrameSizeWithText:text];
    self = [super initWithFrame:CGRectMake(pos.x, pos.y, size.width, size.height)];
    
    if (self) {
        _contentText = text;
        _pos = pos;
        _markDirection = direction;
        self.backgroundColor = [UIColor clearColor];
        [self setupSubView];
        
        if (!_data) {
            _data = [[SNSMarkModel alloc]init];
            _data.contentText = text;
            _data.pos = pos;
            _data.markDirection = direction;
        }
    }
    return self;
}

-(instancetype)initWithDataModel:(SNSMarkModel *)data{
    return [self initWithText:data.contentText pos:data.pos direction:data.markDirection];
}
//-(void)awakeFromNib{
//    NSLog(@"awakeFromNib");
//    
//    [super awakeFromNib];
//    if (self.label) {
//        [self.label addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
//    }
//}


-(void)setupSubView{
    [self addSubview:self.pointer];
    [self addSubview:self.label];
    

    
    

    if (self.markDirection == 0) {
        _bgImage = [[UIImageView alloc]initWithFrame:CGRectMake(28, 4, self.frame.size.width - 28, self.frame.size.height - 8)];
        _bgImage.image = [UIImage imageNamed:@"sns标记"];
        
        _arrow = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"sns标记箭头"]];
        _arrow.frame = CGRectMake(18, 4, 10, 22);
    }else{
        _bgImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 4, self.frame.size.width - 28, self.frame.size.height - 8)];
        _bgImage.image = [UIImage imageNamed:@"sns标记2"];
        
        _arrow = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"sns标记箭头2"]];
        _arrow.frame = CGRectMake(_bgImage.frame.size.width, 4, 10, 22);
    }
    [self addSubview:_bgImage];
    
    [self addSubview:_arrow];
    
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];
    panGesture.minimumNumberOfTouches = 1;
    [self addGestureRecognizer:panGesture];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(popOption:)];
    tapGesture.numberOfTapsRequired = 1;
    [self addGestureRecognizer:tapGesture];
    

    
    [tapGesture requireGestureRecognizerToFail:panGesture];
}
- (void)dealloc{
//    [self.label removeObserver:self forKeyPath:@"text"];
    
}

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    NSLog(@"draw rect ");
    [super drawRect:rect];
    
    [self makePointerView];
    
//    if (self.label) {
//        [self.label addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
//        
//        
//    }

}


-(void)setLabelText:(NSString *)text{
    [self.label setText:text];
    [self setNeedsLayout];
}

-(void)makePointerView{
    //test pointer anime
    static NSMutableArray *shareImages = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        shareImages = [NSMutableArray array];
        for (int i = 11; i <= 43; i ++)
        {
            //将要播放的图片加入数组
            [shareImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"圆点00%02d.png", i]]];
        }
    });
    
    self.pointer.animationImages = shareImages;
    self.pointer.animationDuration = 1.7;  //播放一次动画时长
    self.pointer.animationRepeatCount = -1; // 播放次数，-1 无限
    [self.pointer startAnimating];
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"text"]) {

        [self updateFrameSize];
        
    
    }
}

-(void)setPointerPoint:(CGPoint)point{
    CGRect frame = self.frame;
    frame.origin.x = point.x;
    frame.origin.y = point.y;
    self.frame = frame;
    
    [self updateFrameSize];
}

- (void)handlePan:(UIPanGestureRecognizer *)sender {
    NSLog(@"UIPanGestureRecognizer = %@", sender);
    CGPoint translation = [sender translationInView:self];
    sender.view.center = CGPointMake(sender.view.center.x + translation.x, sender.view.center.y + translation.y);
    [sender setTranslation:CGPointMake(0, 0) inView: self];
    
    self.pos = self.frame.origin;
    self.data.pos = self.pos;
}
- (void)popOption:(UILongPressGestureRecognizer *)sender {
    NSLog(@"UILongPressGestureRecognizer = %@", sender);
    [self.delegate didTouchedLabel:self];

}

-(void)updateFrameSize{
    NSUInteger preferWidth = self.superview.frame.size.width - self.frame.origin.x - klabelInsetRight - klabelInsetRight;
    
    NSAttributedString *labelAttributedString = self.label.attributedText;
    CGRect labelSize = [labelAttributedString boundingRectWithSize:CGSizeMake(preferWidth, FLT_MAX) options:NSStringDrawingUsesLineFragmentOrigin context:nil];
    
    CGRect frame = self.frame;
    frame.size.width = labelSize.size.width +kLabelInsetLeft +klabelInsetRight;
    frame.size.height = labelSize.size.height + kLabelInsetTop + kLabelInsetBottom;
    
    self.frame = frame;
    
    //        CGSize viewSize = [self systemLayoutSizeFittingSize:CGSizeMake(320, FLT_MAX)];
    //        NSLog(@"viewSize = %@",NSStringFromCGSize(viewSize));
//    [self setNeedsLayout];
}

-(CGSize)calcFrameSizeWithText:(NSString *)text{
    NSUInteger preferWidth = SCREEN_WIDTH;
    if (self.superview) {
        if (self.markDirection == 0) {
            preferWidth = self.superview.frame.size.width - self.frame.origin.x - klabelInsetRight - klabelInsetRight;
        }else{
            preferWidth = self.frame.origin.x - kLabelInsetLeft - klabelInsetRight;
        }
    }
    
    
    UIFont *font = [UIFont systemFontOfSize:12];
    
    NSAttributedString *labelString = [[NSAttributedString alloc]initWithString:text attributes:@{NSFontAttributeName:font}];
    CGRect rect = [labelString boundingRectWithSize:CGSizeMake(preferWidth, FLT_MAX) options: NSStringDrawingUsesLineFragmentOrigin context:nil];
    CGSize result = CGSizeMake(rect.size.width+klabelInsetRight+kLabelInsetLeft, rect.size.height + kLabelInsetTop +kLabelInsetBottom);
    
    return result;
}


-(void)flipMark{
    NSLog(@"flipMark");
    
    [UIView animateWithDuration:0.2 animations:^{
        if (_markDirection == 0) {
            CGRect frame = self.frame;
            CGRect newFrame = CGRectMake(frame.origin.x - self.bgImage.frame.size.width, frame.origin.y, frame.size.width, frame.size.height);
            self.frame = newFrame ;
            
            [self.arrow setImage:[UIImage imageNamed:@"sns标记箭头2"]];
            self.arrow.frame = CGRectMake(self.bgImage.frame.size.width, 4, 10, 22);
            
            [self.bgImage setImage:[UIImage imageNamed:@"sns标记2"]];
            self.bgImage.frame = CGRectMake(0, 4, frame.size.width - 28, frame.size.height - 8);
            
            self.label.frame = CGRectMake(6, 8, self.label.frame.size.width, self.label.frame.size.height);
            
            self.pointer.frame = CGRectMake(frame.size.width  - 30, frame.size.height - 30 , 30, 30);
        }else{
            CGRect frame = self.frame;
            CGRect newFrame = CGRectMake(frame.origin.x + self.bgImage.frame.size.width, frame.origin.y, frame.size.width, frame.size.height);
            self.frame = newFrame ;
            
            [self.arrow setImage:[UIImage imageNamed:@"sns标记箭头"]];
            self.arrow.frame = CGRectMake(18, 4, 10, 22);
            
            [self.bgImage setImage:[UIImage imageNamed:@"sns标记"]];
            self.bgImage.frame = CGRectMake(28, 4, frame.size.width - 28, frame.size.height - 8);
            
            self.label.frame = CGRectMake(34, 8, self.label.frame.size.width, self.label.frame.size.height);
            
            self.pointer.frame = CGRectMake(0, 0, 30, 30);
        }
        
    }];
    _markDirection = (_markDirection == SNSMarkRight)?SNSMarkLeft:SNSMarkRight;
    self.data.markDirection = _markDirection;
    self.pos = self.frame.origin;
    self.data.pos = self.pos;
}

#pragma mark - setter & getter
-(UIImageView *)pointer{
    if (!_pointer) {
        
        if (self.markDirection == 0) {
            _pointer = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
        }else{
            CGSize size = self.frame.size;
            _pointer = [[UIImageView alloc]initWithFrame:CGRectMake(size.width  - 30, size.height - 30 , 30, 30)];
        }
    }
    
    return _pointer;
}

-(UILabel *)label{
    if (!_label) {
        NSUInteger preferWidth = SCREEN_WIDTH;
        if (self.superview) {
            if (self.markDirection == 0) {
                preferWidth = self.superview.frame.size.width - self.frame.origin.x - klabelInsetRight - klabelInsetRight;
            }else{
                preferWidth = self.frame.origin.x - kLabelInsetLeft - klabelInsetRight;
            }
        }
        
        
        UIFont *font = [UIFont systemFontOfSize:12];
        NSAttributedString *labelString = [[NSAttributedString alloc]initWithString:self.contentText attributes:@{NSFontAttributeName:font}];
        CGRect rect = [labelString boundingRectWithSize:CGSizeMake(preferWidth, FLT_MAX) options: NSStringDrawingUsesLineFragmentOrigin context:nil];
        CGRect frame;
        if (_markDirection == 0) {
            frame = CGRectMake(34, 8, rect.size.width, rect.size.height);
            
        }else{
            frame = CGRectMake(6, 8, rect.size.width, rect.size.height);
        }
        _label = [[UILabel alloc]initWithFrame:frame];
        _label.numberOfLines = 0;
        _label.attributedText = labelString;
    }

    return _label;
}

-(void)updateData{
    if (self.data) {
        CGSize size = [self calcFrameSizeWithText:self.data.contentText];
        self.frame = CGRectMake(self.data.pos.x, self.data.pos.y, size.width, size.height);
        
        self.label.text = self.data.contentText;
    }
}

- (NSDictionary *)toDictionary{
    return @{kSNSMarkPosX:@(_pos.x), kSNSMarkPosY:@(_pos.y), kSNSMarkDirection:@(_markDirection), kSNSMarkContent:self.label.text};
}
/*
#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    switch (buttonIndex) {
        case 0:
            [self flipMark];
            self.shownActionSheet = NO;
            break;
        case 1:
            [self.viewController performSegueWithIdentifier:kSegueAddMark sender:self];
            
            
            break;
        case 2:
            [self.viewController.markArray removeObject:self.data];
            [self removeFromSuperview];
            
            
            break;

    }
    
}
*/
@end

